package com.zijidelu.luframework.domain.model.entity;

import com.zijidelu.luframework.base.TypeCaster;
import com.zijidelu.luframework.base.bizsig.BizSignature;
import com.zijidelu.luframework.base.model.DataModel;
import com.zijidelu.luframework.base.model.crud.CrudState;
import com.zijidelu.luframework.utils.cache.vault.AbstractGroupedVault;
import com.zijidelu.luframework.utils.cache.vault.ItemVault;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 子实体容器
 *
 * @author ZIJIDELU
 * @datetime 2025/11/17 23:18
 */
public class ChildrenEntityVault<E extends Entity<? extends DataModel>, C extends ChildEntity<E, ? extends DataModel>>
        extends AbstractGroupedVault<Class<C>, C, ChildrenEntityVault.ItemRecord<E, C>> implements TypeCaster {
    private final AtomicInteger globalSeq = new AtomicInteger(0);

    /**
     * 子实体项
     *
     * @param childrenEntity 子实体
     * @param crudState      子实体CRUD状态
     */
    public record ItemRecord<E extends Entity<?>, C extends ChildEntity<E, ?>>(C childrenEntity, CrudState crudState,
                                                                               BizSignature<? extends DataModel> bizSignature,
                                                                               int seq) {
    }

    @SuppressWarnings("unchecked")
    private void registerItem(C childEntity, CrudState crudState, BizSignature<? extends DataModel> bizSignature) {
        Objects.requireNonNull(childEntity, "Child entity cannot be null");
        putItemWithGroup((Class<C>) childEntity.getClass(), childEntity, new ItemRecord<>(childEntity, crudState, bizSignature, globalSeq.incrementAndGet()));
    }

    /**
     * 添加待创建的实体
     *
     * @param entity 子实体
     */
    public void registerCreated(C entity) {
        registerCreated(entity, null);
    }

    public void registerCreated(C entity, BizSignature<? extends DataModel> bizSignature) {
        registerItem(entity, CrudState.CREATE, bizSignature);
    }

    /**
     * 添加待更新的实体
     *
     * @param entity 子实体
     */
    public void registerUpdated(C entity) {
        registerUpdated(entity, null);
    }

    public void registerUpdated(C entity, BizSignature<? extends DataModel> bizSignature) {
        registerItem(entity, CrudState.UPDATE, bizSignature);
    }

    /**
     * 添加待删除的实体
     *
     * @param entity 子实体
     */
    public void registerDeleted(C entity) {
        registerDeleted(entity, null);
    }

    public void registerDeleted(C entity, BizSignature<? extends DataModel> bizSignature) {
        registerItem(entity, CrudState.DELETE, bizSignature);
    }

    /**
     * 添加READ状态的子实体
     *
     * @param entity 子实体
     */
    public void registerRead(C entity) {
        registerRead(entity, null);
    }

    public void registerRead(C entity, BizSignature<? extends DataModel> bizSignature) {
        registerItem(entity, CrudState.READ, bizSignature);
    }

    /**
     * 获取所有更新实体列表
     *
     * @return 所有更新实体列表
     */
    public List<ChildEntity<E, ?>> getUpdatedList() {
        if (isEmpty()) {
            return Collections.emptyList();
        }

        return entrySet().stream()
                .flatMap(entry -> entry.getValue().entrySet().stream())
                .map(Map.Entry::getValue)
                .filter(e -> e.crudState() == CrudState.UPDATE)
                .sorted(Comparator.comparingInt(ItemRecord::seq))
                .map(ItemRecord::childrenEntity)
                .collect(Collectors.toList());
    }

    /**
     * 获取所有创建实体列表
     *
     * @return 所有创建实体列表
     */
    public List<ChildEntity<E, ?>> getCreatedList() {
        if (isEmpty()) {
            return Collections.emptyList();
        }

        return entrySet().stream()
                .flatMap(entry -> entry.getValue().entrySet().stream())
                .map(Map.Entry::getValue)
                .filter(e -> e.crudState() == CrudState.CREATE)
                .sorted(Comparator.comparingInt(ItemRecord::seq))
                .map(ItemRecord::childrenEntity)
                .collect(Collectors.toList());
    }

    /**
     * 获取所有删除实体列表
     *
     * @return 所有删除实体列表
     */
    public List<ChildEntity<E, ?>> getDeletedList() {
        if (isEmpty()) {
            return Collections.emptyList();
        }

        return entrySet().stream()
                .flatMap(entry -> entry.getValue().entrySet().stream())
                .map(Map.Entry::getValue)
                .filter(e -> e.crudState() == CrudState.DELETE)
                .sorted(Comparator.comparingInt(ItemRecord::seq))
                .map(ItemRecord::childrenEntity)
                .collect(Collectors.toList());
    }

    /**
     * 获取所有读取实体列表
     *
     * @return 所有读取实体列表
     */
    public List<ChildEntity<E, ?>> getReadList() {
        if (isEmpty()) {
            return Collections.emptyList();
        }

        return entrySet().stream()
                .flatMap(entry -> entry.getValue().entrySet().stream())
                .map(Map.Entry::getValue)
                .filter(e -> e.crudState() == CrudState.READ)
                .sorted(Comparator.comparingInt(ItemRecord::seq))
                .map(ItemRecord::childrenEntity)
                .collect(Collectors.toList());
    }

    /**
     * 获取子实体项缓存
     *
     * @param groupKey 子实体类型
     * @return 子实体项缓存
     */
    @Override
    public ItemVault<C, ItemRecord<E, C>> getItem(Class<C> groupKey) {
        return super.getItem(groupKey);
    }

    @Override
    public ItemVault<C, ItemRecord<E, C>> putItem(Class<C> itemKey, ItemVault<C, ItemRecord<E, C>> item) {
        return super.putItem(itemKey, item);
    }

    @Override
    public void clearVault() {
        super.clearVault();
    }
}
